setState()

  • Code

    setState() is a method used within stateful widgets to update the state and trigger a rebuild of the UI. When you call setState(),

    
    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: CounterApp(),
        );
      }
    }
    
    class CounterApp extends StatefulWidget {
      @override
      _CounterAppState createState() => _CounterAppState();
    }
    
    class _CounterAppState extends State<CounterApp> {
      int _counter = 0;
    
      void _incrementCounter() {
        // Updating the counter value using setState
        setState(() {
          _counter++;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Counter App'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  'Counter:',
                  style: TextStyle(fontSize: 20),
                ),
                Text(
                  '$_counter',
                  style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ),
        );
      }
    }
    
    
    

    The UI, specifically the Text widget displaying the counter value, rebuilds whenever setState() is called, reflecting the updated value.
    setState() is crucial for managing state changes within stateful widgets and ensuring that the UI reflects the updated state data. Always ensure that the code within setState() is modifying the state variable so that Flutter can correctly update the UI.